package com.lagou.servlet;

import com.lagou.bean.User;
import com.lagou.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置响应输出编码，避免中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 2.获取请求中的用户名和密码信息并打印出来
        String userName = request.getParameter("userName");
        System.out.println("获取到的用户名是" + userName);
        String password = request.getParameter("password");
        System.out.println("获取到的密码是" + password);
        String auto = request.getParameter("auto");
        System.out.println("是否勾选7免"+auto);

        // 3.创建UserService类型的对象去实现数据的校验功能
        UserService userService = new UserService();
        User user = userService.loginUserService(new User(userName, password));
        //4.验证失败重新回到登录界面
        if (user == null) {
            request.setAttribute("error", "用户名和密码输入错误");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request, response);
        //7.判断是否勾选免登陆
        } else if (null != auto) {
            //8.创建Cookie,将用户名密码存入Cookie
            Cookie cookie = new Cookie("userName", userName);
            Cookie cookie1 = new Cookie("password", password);
            cookie.setMaxAge(60*60*24*7);
            cookie1.setMaxAge(60*60*24*7);
            response.addCookie(cookie);
            response.addCookie(cookie1);
            //9.向session内存入一条数据,用于过滤
            request.getSession().setAttribute("userName",userName);
            request.getSession().setAttribute("login","login");
            response.sendRedirect("main.jsp");
        } else {
            request.getSession().setAttribute("userName",userName);
            request.getSession().setAttribute("login","login");
            response.sendRedirect("main.jsp");
        }


    }
}
